package com.hm.service.impl.wx;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.hm.service.framework.base.BaseServiceImpl;
import com.hm.service.service.wx.TencentMapService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://lbs.qq.com/service/webService/webServiceGuide/address/Gcoder">腾讯地图服务api</a>
 */

@Service
public class TencentMapServiceImpl extends BaseServiceImpl implements TencentMapService {
    private static final Logger logger = LoggerFactory.getLogger(TencentMapServiceImpl.class);

    //腾讯地图应用key
    private static final String tMapKey = "TG7BZ-JMEC4-U5LUG-FIXNM-6HZLE-3IBG5";

    //缓存时间-单位 秒
    private static final int SurvivalTime = 60 * 60;

    @Qualifier("OkHttpClient")
    public OkHttpClient okHttpClient;

    @Qualifier("JedisPool")
    private final JedisPool jedisPool;

    public TencentMapServiceImpl(OkHttpClient okHttpClient, JedisPool jedisPool) {
        this.okHttpClient = okHttpClient;
        this.jedisPool = jedisPool;
    }

    @Override
    public String LongitudeAndLatitudeToAddress(String longitude, String latitude) {
        //根据经纬度缓存逆地理编码数据
        String cacheKey = "cache-" + longitude + "-" + latitude;
        //get请求
        String reqUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude + "," + longitude + "&key=" + tMapKey;
        Request build = new Request.Builder().url(reqUrl).build();
        try (Jedis jedis = jedisPool.getResource(); Response response = okHttpClient.newCall(build).execute()) {
            boolean exists = jedis.exists(cacheKey);
            if (exists) {
                String data = jedis.get(cacheKey);
                //存在则说明没过期且有效
                if (data != null && !data.isEmpty()) {
                    //json字符串转map
                    Map<String, String> resp = JSON.parseObject(data, new TypeReference<HashMap<String, String>>() {
                    });
                    return generateSucceed(resp);
                }
            }
            //不存在则说明过期了->从新获取
            ResponseBody resBody = response.body();
            if (response.isSuccessful() && resBody != null) {
                String jsonString = resBody.string();
                JSONObject jsonObject = JSONObject.parseObject(jsonString);
                logger.error("逆地理编码成功:{}", jsonObject);
                JSONObject result = jsonObject.getJSONObject("result");
                //获取描述性地址
                JSONObject formattedAddresses = result.getJSONObject("formatted_addresses");
                String standardAddress = formattedAddresses.getString("standard_address");
                String recommend = formattedAddresses.getString("recommend");
                //获取坐标相对位置参考
                JSONObject addressReference = result.getJSONObject("address_reference");
                JSONObject town = addressReference.getJSONObject("town");//获取乡道/街道（四级行政区划）
                String id = town.getString("id");
                String title = town.getString("title");//名称
                if (id == null || !id.equals("441881001")) {
                    //不在‘英城街道’区域内
                    Map<String, String> resp = new HashMap<>();
                    resp.put("recommend", "尚未开通<" + title + ">区域");
                    resp.put("status", "001");
                    //缓存1小时
                    String data = JSON.toJSONString(resp);
                    jedis.setex(cacheKey, SurvivalTime, data);
                    return generateSucceed(resp);
                }
                //构建响应体
                Map<String, String> resp = new HashMap<>();
                resp.put("recommend", recommend);
                resp.put("standardAddress", standardAddress);
                resp.put("status", "000");
                //缓存1小时
                String data = JSON.toJSONString(resp);
                jedis.setex(cacheKey, SurvivalTime, data);
                return generateSucceed(resp);
            } else {
                logger.error(" ");
                return generateFail("逆地理编码成功获取resBody为null！！");
            }
        } catch (Exception e) {
            return generateFail("逆地理编码异常：Exception: " + e.getMessage());
        }
    }
}
